package top.lauwen.handlertm;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {
    private ProgressBar progressBar = null;
    private Button btnStart = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        btnStart = (Button) findViewById(R.id.btn);
        btnStart.setOnClickListener(new btnStartListener());
    }
    class btnStartListener implements View.OnClickListener{
        @Override
        public void onClick(View v){
            progressBar.setVisibility(View.VISIBLE);
            progressBarHandler.post(updateThread);
        }
    }
    Handler progressBarHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            progressBar.setProgress(msg.arg1);
            progressBarHandler.post(updateThread);
        }

    };
    Runnable updateThread = new Runnable() {
        private int i = 0;

        @Override
        public void run() {
            System.out.println("Start Thread");
            i = i + 10;
            Message msg = progressBarHandler.obtainMessage();
            msg.arg1 = i;
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            progressBarHandler.sendMessage(msg);
            if(i == 100){
                progressBarHandler.removeCallbacks(updateThread);
            }
        }
    };
}
